package com.aliyun.heiyu.powermaster.server.util;

import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.powermaster.proto.DeleteNodeDataReply;
import com.aliyun.heiyu.powermaster.proto.GetNodeDataReply;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.SerializableSerializer;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class ZkClientUtil {

    private static Logger logger = LoggerFactory.getLogger(ZkClientUtil.class);

    private final static String CONNECTSTRING = Configuration.IP + ":" + PropertiesUtil.getValue("zoo.properties", "clientPort");

    private static boolean zkSwitch = Boolean.valueOf(PropertiesUtil.getValue("serverIp.properties", "zkSwitch"));

    public static void addNodeData(String path, String data, int mode) {
        ZkClient zkClient =  new ZkClient(CONNECTSTRING, 5000, 5000, new SerializableSerializer());
        try {
            if (null == path || path.isEmpty() || null == data || data.isEmpty()) {
                logger.error("parameter is null or empty");
            }
            if (!zkClient.exists(path)) {
                if (mode == 0) {
                    zkClient.create(path, data, CreateMode.PERSISTENT);
                } else {
                    zkClient.create(path, data, CreateMode.EPHEMERAL);
                }
            }
            logger.error("节点路径" + path + "已存在");
        }catch (Exception e){
            logger.error("======添加节点报错了==========="+e.getMessage());
        } finally {
            if(null != zkClient) {
                zkClient.close();
            }
        }
    }


    public static GetNodeDataReply getNodeData(String path) {
        ZkClient zkClient =  new ZkClient(CONNECTSTRING, 5000, 5000, new SerializableSerializer());
        GetNodeDataReply.Builder builder = GetNodeDataReply.newBuilder();

        try {
            if (null == path || path.isEmpty()) {
                logger.error("path  is null or empty");
                return builder.setErrCode(502).setErrMsg("path  is null or empty").build();
            }
            String data = null;
            if (zkClient.exists(path)) {
                data = zkClient.readData(path).toString();
                return builder.setData(data).build();
            } else {
                logger.error("节点路径:" + path + ",不存在");
                return builder.setErrCode(503).setErrMsg("节点路径:" + path + ",不存在").build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取节点路径：" + path + "数据出现问题");
        } finally {
            if(null != zkClient) {
                zkClient.close();
            }
        }
        return builder.setErrCode(504).setErrMsg("获取节点路径：" + path + "数据出现问题").build();
    }

    public static void updateNodeData(String path, String data) {
        ZkClient zkClient =  new ZkClient(CONNECTSTRING, 5000, 5000, new SerializableSerializer());

        try {
            if (null == path || path.isEmpty() || null == data || data.isEmpty()) {
                logger.error("parameter is null or empty");
            }

            if (zkClient.exists(path)) {
                zkClient.writeData(path, data);
            } else {
                addNodeData(path, data, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改节点路径：" + path + "数据出现问题");
        } finally {
            if(null != zkClient) {
                zkClient.close();
            }
        }
    }


    public static DeleteNodeDataReply deleteNodeData(String path) {
        ZkClient zkClient =  new ZkClient(CONNECTSTRING, 5000, 5000, new SerializableSerializer());

        DeleteNodeDataReply.Builder builder = DeleteNodeDataReply.newBuilder();
        try {
            if (null == path || path.isEmpty()) {
                logger.error("path  is null or empty");
                return builder.setErrCode(502).setErrMsg("path  is null or empty").build();
            }

            if (zkClient.exists(path)) {
                List<String> children = zkClient.getChildren(path);
                if (children.isEmpty()) {
                    zkClient.delete(path);
                    return builder.build();
                } else {
                    for (String subPath : children) {
                        deleteNodeData(path + "/" + subPath);
                    }
                    return builder.build();
                }
            } else {
                logger.error("节点路径:" + path + ",不存在");
                return builder.setErrCode(503).setErrMsg("节点路径:" + path + ",不存在").build();
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除节点：" + path + "出现问题");
        } finally {
            if(null != zkClient) {
                zkClient.close();
            }
        }
        return builder.setErrCode(507).setErrMsg("删除节点：" + path + "出现问题").build();
    }

    public static Boolean checkLeader(){
        if(!zkSwitch){
            return true;
        }
        try {
            GetNodeDataReply nodeData = getNodeData("/leader");
            String leaderIp = nodeData.getData().split(":")[0];
            return Configuration.IP.equals(leaderIp);
        } catch (Exception e){
            return true;
        }
    }
}
